const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const cors = require('cors');
const bodyParser = require('body-parser');
const multer = require('multer');
const path = require('path');
// 导入路由模块
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const categoryRoutes = require('./routes/category');
const productRoutes = require('./routes/product');
const cartRoutes = require('./routes/cart');
const orderRoutes = require('./routes/order');
const messageRoutes = require('./routes/message');
const mysteryBoxRoutes = require('./routes/mysteryBox');
const commentRoutes = require('./routes/comment');
const followRoutes = require('./routes/follow');

// 文件上传配置
// const storage = multer.diskStorage({
//   destination: (cb) => {
//     cb(null, 'uploads/');
//   },
//   filename: (file, cb) => {
//     cb(null, Date.now() + path.extname(file.originalname));
//   }
// });

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/upload', express.static(path.join(__dirname, 'upload')));

// 使用路由
// API路由注册 - 按功能模块划分
// 1. 用户认证相关路由 (登录/注册/刷新令牌)...
app.use('/api/auth', authRoutes);
// 2. 用户信息相关路由 (个人资料/头像/地址管理)...
app.use('/api/user', userRoutes);
// 3. 商品分类相关路由 (分类列表/详情)...
app.use('/api/categories', categoryRoutes);
// 4. 商品相关路由 (商品列表/详情/搜索)
app.use('/api/products', productRoutes);
// 5. 购物车相关路由 (添加/删除/修改购物车)
app.use('/api/cart', cartRoutes);
// 6. 订单相关路由 (创建订单/支付/订单历史)
app.use('/api/orders', orderRoutes);
// 7. 留言相关路由 (商品留言/回复)
app.use('/api/messages', messageRoutes);
// 8. 神秘盒子相关路由 (获取/打开/刷新)
app.use('/api/mysteryBox', mysteryBoxRoutes);
// 9. 评论相关路由 (创建/获取/更新/删除)
app.use('/api/comments', commentRoutes);
// 10. 关注相关路由 (关注/取消关注/获取关注列表)
app.use('/api/follows', followRoutes);

// 错误处理中间件
app.use((err, res) => {
  console.error(err);
  res.status(500).json({ code: 500, message: 'Internal server error', error: err.message });
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});